"""  
       @File     : predict.py
       @IDE      : PyCharm
       @Author   : 陈引弟
       @Date     : 2025/3/8 14:42
       @Desc     : 
=========================================================   
"""

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier

# 数据加载
data = pd.read_csv('F:\python\基于大数据的天气预测分析系统\model\lishiweather.csv')

# 提取特征值
selected_features = ['date','wind','city','wearther']
data = data[selected_features]

# 数据处理
data['date'] = pd.to_datetime(data['date'])

# 编码为数字
le = LabelEncoder()
le2 = LabelEncoder()
le3 = LabelEncoder()
data['wind'] = le.fit_transform(data['wind'])
data['city'] = le2.fit_transform(data['city'])
data['wearther'] = le3.fit_transform(data['wearther'])

data['day_of_year'] = data['date'].dt.dayofyear
data['day_of_week'] = data['date'].dt.dayofweek
data['month'] = data['date'].dt.month

# 选择变量
X = data[['day_of_year','day_of_week','month','wind','city']]
y = data['wearther']

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建随机森林分类模型，减少树的数量和深度
clf = RandomForestClassifier(n_estimators=50, max_depth=10, random_state=42)

# 训练模型
clf.fit(X_train, y_train)

def preModel(model, *args):
    print(args)
    date = pd.to_datetime(args[0][0])
    day_of_year = date.day_of_year
    day_of_week = date.day_of_week
    month = date.month

    wind = [le.transform([args[0][1]])[0]]
    city = [le2.transform([args[0][2]])[0]]
    sample_date = pd.DataFrame({
        'day_of_year': [day_of_year],
        'day_of_week': [day_of_week],
        'month': [month],
        'wind': wind,
        'city': city
    })

    predicted_weather = clf.predict(sample_date)
    predicted_weather = le3.inverse_transform(predicted_weather)
    print(predicted_weather)
    return predicted_weather[0]

preModel(clf, ['2025-01-01', '东北风', '北京'])